import com.sun.net.httpserver.HttpExchange;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.HashMap;
import java.util.Map;
import com.google.gson.Gson;

import LunaServer.core.LunaServer;
import LunaServer.routing.Route;
/**
 * 根路由处理器
 * 处理根路径"/"的请求
 */
public class RootRoute implements Route {

    // 路由构造时必须携带服务器。
    private final LunaServer server;
    public RootRoute(LunaServer server) {
        this.server = server;
    }

    /**
     * 处理HTTP请求
     * 
     * @param exchange HttpExchange对象
     * @return 响应内容
     */
    public String handleRequest(HttpExchange exchange) throws IOException {
        // 读取请求体
        String requestBody = "";
        try (InputStream is = exchange.getRequestBody()) {
            requestBody = new String(is.readAllBytes(), StandardCharsets.UTF_8);
        }

        // 解析请求体获取token
        Gson gson = new Gson();
        Map<String, String> requestData = new HashMap<>();
        String token = "undefined";
        
        try {
            requestData = gson.fromJson(requestBody, Map.class);
            token = requestData.getOrDefault("token", "undefined");
        } catch (Exception e) {
            // 如果解析失败，使用默认值
        }

        // 使用Gson构造响应
        Map<String, Object> responseMap = new HashMap<>();
        responseMap.put("token", token);
        responseMap.put("time", Instant.now().toString());

        String response = gson.toJson(responseMap);

        // 设置响应头
        exchange.getResponseHeaders().set("Content-Type", "application/json");
        exchange.sendResponseHeaders(200, response.getBytes(StandardCharsets.UTF_8).length);

        return response;
    }
}